package interface_layer;

import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import processing_layer.SessionTracker;

/**
 * This session monitor is used in order to track "non-user" session
 * terminations. When a user logs in, or logs out, our code handles some
 * of the invalidation of the session. In cases where the server decides
 * to invalidate the session, our code is not called. Since there's an inner
 * session maintainer in our code, we use this monitor to update that
 * maintainer accordingly when a session is ended.
 */
public class SessionMonitor implements HttpSessionListener {

    /**
     * Default constructor. 
     */
    public SessionMonitor()
    {
        super();
    }

	/**
     * @see HttpSessionListener#sessionCreated(HttpSessionEvent)
     */
    public void sessionCreated(HttpSessionEvent sesionEvent)
    {
    	/* A session is created in our case when a user logs in / registers... */
    }

	/**
     * @see HttpSessionListener#sessionDestroyed(HttpSessionEvent)
     */
    public void sessionDestroyed(HttpSessionEvent sessionEvent)
    {
    	/* We're using this one in case the server has a timeout for each session
    	 * Since all our code fetches the username attribute, invalidation from the
    	 * server will automatically log-out the user... */
    	
        String username = (String) sessionEvent.getSession().getAttribute("username");
        if (null == username)
        {
        	System.out.println("Emm... Session invalidated for null?");
        }
        else
        {
        	System.out.println("Session invalidation for " + username);
        	SessionTracker.removeDisconnectedUser(username);
        }
    }
	
}
